package com.example.aiinterview.controller;

import com.example.aiinterview.model.*;
import com.example.aiinterview.service.AIService;
import com.example.aiinterview.service.InterviewService;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 聊天API控制器
 * 处理实时聊天相关的REST接口
 */
@Slf4j
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final InterviewService interviewService;
    private final UserService userService;
    private final AIService aiService;

    /**
     * 发送聊天消息
     */
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendMessage(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 参数验证
            ValidationResult validation = validateSendMessageRequest(request, authentication);
            if (!validation.isValid()) {
                response.put("success", false);
                response.put("error", validation.getErrorMessage());
                return ResponseEntity.badRequest().body(response);
            }

            // 处理聊天消息
            ChatProcessingResult result = processChatMessage(validation.getInterview(),
                    validation.getMessage(), authentication);

            response.put("success", true);
            response.put("aiResponse", result.getAiResponse());
            response.put("interviewCompleted", result.isCompleted());

            log.info("消息处理成功，interviewId: {}", validation.getInterview().getId());

        } catch (Exception e) {
            log.error("发送消息时发生异常", e);
            response.put("success", false);
            response.put("error", "服务器内部错误，请稍后重试");
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 获取聊天历史
     */
    @GetMapping("/history/{interviewId}")
    public ResponseEntity<Map<String, Object>> getChatHistory(
            @PathVariable Long interviewId,
            Authentication authentication) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 参数验证
            ValidationResult validation = validateChatHistoryRequest(interviewId, authentication);
            if (!validation.isValid()) {
                response.put("success", false);
                response.put("error", validation.getErrorMessage());
                return ResponseEntity.badRequest().body(response);
            }

            // 获取聊天记录
            List<Map<String, Object>> messages = getFormattedChatMessages(validation.getInterview());
            response.put("success", true);
            response.put("messages", messages);

            log.debug("获取聊天历史成功，interviewId: {}, 消息数量: {}", interviewId, messages.size());

        } catch (Exception e) {
            log.error("获取聊天历史失败，interviewId: {}", interviewId, e);
            response.put("success", false);
            response.put("error", "获取聊天历史失败");
        }

        return ResponseEntity.ok(response);
    }

    // ========== 私有辅助方法 ==========

    /**
     * 验证发送消息请求
     */
    private ValidationResult validateSendMessageRequest(Map<String, Object> request,
                                                        Authentication authentication) {
        try {
            Object interviewIdObj = request.get("interviewId");
            Object messageObj = request.get("message");

            if (interviewIdObj == null) {
                return ValidationResult.error("面试ID不能为空");
            }

            if (messageObj == null || messageObj.toString().trim().isEmpty()) {
                return ValidationResult.error("消息内容不能为空");
            }

            Long interviewId = Long.valueOf(interviewIdObj.toString());
            String message = messageObj.toString().trim();

            User user = userService.findByUsername(authentication.getName());
            if (user == null) {
                return ValidationResult.error("用户不存在");
            }

            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ValidationResult.error("面试不存在，ID: " + interviewId);
            }

            if (!isInterviewAccessible(interview, user)) {
                return ValidationResult.error("无权访问此面试");
            }

            return ValidationResult.success(interview, message);

        } catch (NumberFormatException e) {
            return ValidationResult.error("面试ID格式错误");
        } catch (Exception e) {
            log.error("验证发送消息请求失败", e);
            return ValidationResult.error("请求验证失败");
        }
    }

    /**
     * 验证聊天历史请求
     */
    private ValidationResult validateChatHistoryRequest(Long interviewId,
                                                        Authentication authentication) {
        try {
            if (interviewId == null || interviewId <= 0) {
                return ValidationResult.error("面试ID不能为空");
            }

            User user = userService.findByUsername(authentication.getName());
            if (user == null) {
                return ValidationResult.error("用户不存在");
            }

            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ValidationResult.error("面试不存在，ID: " + interviewId);
            }

            if (!isInterviewAccessible(interview, user)) {
                return ValidationResult.error("无权访问此面试");
            }

            return ValidationResult.success(interview, null);

        } catch (Exception e) {
            log.error("验证聊天历史请求失败", e);
            return ValidationResult.error("请求验证失败");
        }
    }

    /**
     * 处理聊天消息
     */
    private ChatProcessingResult processChatMessage(Interview interview, String userMessage,
                                                    Authentication authentication) {
        // 保存用户消息
        ChatMessage userChatMessage = createChatMessage(interview, userMessage,
                ChatMessage.MessageSender.USER);
        interview.addChatMessage(userChatMessage);

        // 生成AI回复
        String aiResponse = generateAIResponse(interview, userMessage);

        // 更新问题进度
        updateQuestionProgress(interview);

        // 保存AI回复
        ChatMessage aiChatMessage = createChatMessage(interview, aiResponse,
                ChatMessage.MessageSender.AI);
        interview.addChatMessage(aiChatMessage);

        // 检查面试是否完成
        boolean completed = checkInterviewCompletion(interview);
        if (completed) {
            completeInterview(interview);
        }

        interviewService.saveInterview(interview);

        return new ChatProcessingResult(aiResponse, completed);
    }

    /**
     * 生成AI回复
     */
    private String generateAIResponse(Interview interview, String userMessage) {
        try {
            String context = buildAIResponseContext(interview, userMessage);
            return aiService.generateResponse(context);
        } catch (Exception e) {
            log.error("生成AI回复失败", e);
            return "抱歉，我遇到了一些技术问题。请稍后重试。";
        }
    }

    /**
     * 构建AI回复上下文
     */
    private String buildAIResponseContext(Interview interview, String userMessage) {
        StringBuilder context = new StringBuilder();
        context.append("你是一个专业的面试官，正在对候选人进行面试。\n");
        context.append("职位：").append(interview.getJobPosition() != null ? interview.getJobPosition() : "未指定").append("\n");
        context.append("候选人简历概括：").append(interview.getResumeSummary() != null ? interview.getResumeSummary() : "无简历信息").append("\n");
        context.append("当前是第").append(interview.getCurrentQuestionNumber() != null ? interview.getCurrentQuestionNumber() : 1)
                .append("个问题，总共").append(interview.getTotalQuestions() != null ? interview.getTotalQuestions() : 5).append("个问题。\n\n");

        // 添加对话历史
        appendChatHistory(context, interview);
        context.append("候选人刚才的回答：").append(userMessage).append("\n");

        // 根据问题进度调整提示
        appendProgressBasedPrompt(context, interview);

        return context.toString();
    }

    /**
     * 添加对话历史
     */
    private void appendChatHistory(StringBuilder context, Interview interview) {
        context.append("面试对话历史：\n");
        if (interview.getChatMessages() != null && !interview.getChatMessages().isEmpty()) {
            List<ChatMessage> recentMessages = interview.getChatMessages().stream()
                    .filter(msg -> msg != null && msg.getContent() != null)
                    .sorted((m1, m2) -> m2.getTimestamp().compareTo(m1.getTimestamp()))
                    .limit(10)
                    .collect(Collectors.toList());

            for (ChatMessage msg : recentMessages) {
                String sender = msg.getSender() == ChatMessage.MessageSender.USER ? "候选人" : "面试官";
                context.append(sender).append("：").append(msg.getContent()).append("\n");
            }
        } else {
            context.append("暂无对话历史\n");
        }
        context.append("\n");
    }

    /**
     * 根据进度添加提示
     */
    private void appendProgressBasedPrompt(StringBuilder context, Interview interview) {
        Integer current = interview.getCurrentQuestionNumber();
        Integer total = interview.getTotalQuestions();

        if (current == 1) {
            context.append("请根据简历内容，提出第一个面试问题。问题应该与职位相关，能够评估候选人的专业技能和经验。");
        } else if (current < total) {
            context.append("请根据候选人的回答，提出下一个面试问题。问题应该深入评估候选人的能力，可以是技术问题、行为问题或情景问题。");
        } else {
            context.append("这是最后一个问题。请根据候选人的回答，提出一个总结性的问题，然后结束面试。");
        }
    }

    /**
     * 更新问题进度
     */
    private void updateQuestionProgress(Interview interview) {
        if (interview.getCurrentQuestionNumber() < interview.getTotalQuestions()) {
            interview.setCurrentQuestionNumber(interview.getCurrentQuestionNumber() + 1);
        }
    }

    /**
     * 完成面试
     */
    private void completeInterview(Interview interview) {
        interview.setStatus(Interview.InterviewStatus.COMPLETED);
        interview.setEndTime(LocalDateTime.now());
        generateFinalEvaluation(interview);
        log.info("面试完成，interviewId: {}", interview.getId());
    }

    /**
     * 检查面试是否可访问
     */
    private boolean isInterviewAccessible(Interview interview, User user) {
        return interview != null &&
                interview.getUser() != null &&
                interview.getUser().getId().equals(user.getId());
    }

    /**
     * 创建聊天消息
     */
    private ChatMessage createChatMessage(Interview interview, String content,
                                          ChatMessage.MessageSender sender) {
        ChatMessage message = new ChatMessage();
        message.setInterview(interview);
        message.setSender(sender);
        message.setContent(content);
        message.setTimestamp(LocalDateTime.now());
        return message;
    }

    /**
     * 获取格式化的聊天消息
     */
    private List<Map<String, Object>> getFormattedChatMessages(Interview interview) {
        return interview.getChatMessages().stream()
                .sorted((m1, m2) -> m1.getTimestamp().compareTo(m2.getTimestamp()))
                .map(msg -> {
                    Map<String, Object> msgMap = new HashMap<>();
                    msgMap.put("sender", msg.getSender().name().toLowerCase());
                    msgMap.put("content", msg.getContent());
                    msgMap.put("timestamp", msg.getTimestamp());
                    return msgMap;
                })
                .collect(Collectors.toList());
    }

    // 原有的 checkInterviewCompletion、generateFinalEvaluation、extractScore 方法保持不变
    // ...（原有实现）

    // ========== 内部辅助类 ==========

    /**
     * 验证结果封装类
     */
    private static class ValidationResult {
        private final boolean valid;
        private final String errorMessage;
        private final Interview interview;
        private final String message;

        private ValidationResult(boolean valid, String errorMessage, Interview interview, String message) {
            this.valid = valid;
            this.errorMessage = errorMessage;
            this.interview = interview;
            this.message = message;
        }

        public static ValidationResult error(String errorMessage) {
            return new ValidationResult(false, errorMessage, null, null);
        }

        public static ValidationResult success(Interview interview, String message) {
            return new ValidationResult(true, null, interview, message);
        }

        // getters...
        public boolean isValid() { return valid; }
        public String getErrorMessage() { return errorMessage; }
        public Interview getInterview() { return interview; }
        public String getMessage() { return message; }
    }

    /**
     * 聊天处理结果封装类
     */
    private static class ChatProcessingResult {
        private final String aiResponse;
        private final boolean completed;

        public ChatProcessingResult(String aiResponse, boolean completed) {
            this.aiResponse = aiResponse;
            this.completed = completed;
        }

        // getters...
        public String getAiResponse() { return aiResponse; }
        public boolean isCompleted() { return completed; }
    }
}